package com.stxx.stiot2.service.impl;

import cn.hutool.core.util.StrUtil;
import com.stxx.framwork.constants.LogicType;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.framwork.tran.TranUtils;
import com.stxx.framwork.utils.StoreUtils;
import com.stxx.stiot2.domain.EventLog;
import com.stxx.stiot2.domain.Scene;
import com.stxx.stiot2.domain.Terminal;
import com.stxx.stiot2.service.EventLogService;
import com.stxx.stiot2.service.SceneService;
import com.stxx.stiot2.service.tran.TerminalTranService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.sql.SqlBuilder;

import java.sql.SQLException;
import java.util.*;

/**
 * @author Fuzhenlei
 * @date 2025/01/15 16:41
 */
@Component
public class EventLogServiceImpl implements EventLogService {
    @Inject
    StoreUtils storeUtils;

    private static final String tranField = "terminalCode";
    private static final String tranFieldScene = "sceneId";
    @Inject
    TerminalTranService terminalTranService;
    @Inject
    SceneService sceneService;

    @Init
    public void start(){
        this.configLogic(EventLog::getName, LogicType.LIKE);
    }

    @Override
    public EventLog queryById(String id) {
        try {
            EventLog r = storeUtils.selectById(id,EventLog.class);
            tran(Arrays.asList(r));
            return r;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(EventLog bean) throws SQLException {
        if(bean.getId()==null){
            bean.setId(UUID.randomUUID().toString().replace("-",""));
        }
        validEntityBeforeSave(bean);
        return storeUtils.insert(bean);
    }

    @Override
    public int update(EventLog bean) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.update(bean);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EventLog bean){

    }





    @Override
    public int delete(String name) throws SQLException {
        return storeUtils.delete(EventLog.class,name);
    }

    @Override
    public int deleteByIds(String[] ids) throws SQLException {
        return storeUtils.deleteByIds(EventLog.class, ids);
    }

    @Override
    public List<EventLog> list(EventLog obj) throws SQLException {
        List<EventLog> list = storeUtils.selectList(EventLog.class,obj);
        tran(list);
        return list;
    }

    @Override
    public PageResult<EventLog> pageList(EventLog obj, PageQuery pageQuery) throws SQLException {
        PageResult<EventLog> result = storeUtils.selectPageList(EventLog.class,obj,pageQuery);
        tran(result.getData());
        return result;
    }

    @Override
    public PageResult<EventLog> pageListByDeviceId(String deviceId, PageQuery pageQuery) throws SQLException {
        SqlBuilder sb = new SqlBuilder();
        sb.append("from ").append(StoreUtils.getTableName(EventLog.class))
                .append(" a left join ")
                .append(StoreUtils.getTableName(Terminal.class)).append(" t on t.code = a.terminal_code")
                .append(" where t.device_id = ?",deviceId);
        sb.backup();
        sb.insert("select a.* ");
        if(StrUtil.isNotEmpty(pageQuery.getOrderByColumn())){
            if(StrUtil.isBlank(pageQuery.getIsAsc())){
                pageQuery.setIsAsc("asc");
            }
            sb.append(" order by ")
                    .append(pageQuery.getOrderByColumn())
                    .append(" ")
                    .append(pageQuery.getIsAsc());
        }
        sb.append(" limit ?,? ", (pageQuery.getPageNum()-1)*pageQuery.getPageSize(),pageQuery.getPageSize()); //分页获取列表

        List<EventLog> list = storeUtils.sql(sb).queryRowList(EventLog.class);
        //回滚（可以复用备份前的代码构建）
        sb.restore();
        sb.insert("select count(*)  ");
        //查询总数
        Long total = Long.parseLong(storeUtils.sql(sb).queryValue().toString());
        PageResult<EventLog> pageResult = new PageResult(list,total);
        return pageResult;
    }

    private void tran(List<EventLog> beanList){
        TranUtils.build().add(tranField,terminalTranService)
                .add(tranFieldScene,(tranFieldScene,ids) -> {
            Map<String,Map<String,Object>> map = new HashMap<>();
            SqlBuilder sb = new SqlBuilder();
            sb.append("select id,name from ").append(StoreUtils.getTableName("scene")).append(" where id in (?...)",ids);
            try {
                List<Scene> list = storeUtils.sql(sb).queryRowList(Scene.class);
                if(list!=null){
                    list.forEach(item->{
                        Map<String,Object> map2 = new HashMap<>();
                        map2.put("sceneName",item.getName());
                        map.put(item.getId()+"",map2);
                    });
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return map;
        }).add("actionType").tran(beanList);
    }
}
